package com.question.common.handler;

import com.alibaba.fastjson2.JSON;
import com.question.common.constants.SecurityConstants;
import com.question.common.model.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 鉴权失败处理
 *
 * @author star
 * @since 2022/7/22
 */
@Slf4j
@Component
public class FailAuthEntryPointHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        //验证为未登陆状态会进入此方法，认证错误
        log.warn("{}-认证失败：{}", request.getServletPath(), e.getMessage());
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        ResponseVO<String> result = new ResponseVO<>();
        result.setCode(HttpStatus.UNAUTHORIZED.value());
        result.setMessage(SecurityConstants.FAIL_AUTH);
        String body = JSON.toJSONString(result);
        printWriter.write(body);
        printWriter.flush();
    }
}
